package com.example.util;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	
	public static String replace(String source, String searchValue, String replaceValue) {
		return replace(source, searchValue, replaceValue, 0);
	}
	
	public static String replace(String source, String searchValue, String replaceValue, int startIndex) {
		int index = source.indexOf(searchValue, startIndex);
		if (index > -1)
			return new StringBuffer().append(source.substring(startIndex, index)).append(replaceValue).append(source.substring(index + searchValue.length())).toString();
		else
			return source;
	}
	
	public static String replaceAll(String source, String searchValue, String replaceValue) {
		return replaceAll(source, searchValue, replaceValue, 0);
	}
	
	public static String replaceAll(String source, String searchValue, String replaceValue, int startIndex) {
		int index = source.indexOf(searchValue, startIndex);
		int endIndex = index + searchValue.length(); 
		if (index > -1)
			return replaceAll(new StringBuffer().append(source.substring(0, index)).append(replaceValue).append(source.substring(endIndex)).toString(), searchValue, replaceValue, endIndex);
		else
			return source;
	}
	
	public static boolean patternMatch (String str, String regex) {
		if (str == null)
			return false;
		
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	public static ArrayList<String> patternFind (String str, String regex) {
		ArrayList<String> matchList = new ArrayList<String>();
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		while (m.find()) {
			matchList.add(str.substring(m.start(), m.end()));
		}
		
		return matchList;
	}
	
	public static Map<String, String> getQueryMap(String query)  
	{  
	    String[] params = query.split("&");  
	    Map<String, String> map = new HashMap<String, String>();  
	    for (String param : params)  
	    {  
	        String name = param.split("=")[0];  
	        String value = param.split("=")[1];  
	        if(value ==null)
	        	value = "";
	        map.put(name, value);  
	    }  
	    return map;  
	}  
	public static Map<String, String> getCookieMap(String query)  
	{  
	    String[] params = query.split(";");  
	    Map<String, String> map = new HashMap<String, String>();
	    for (String param : params)  
	    {  
	    	try {
	    		String name = param.split("=")[0];  
		        String value = param.split("=")[1];  
		        map.put(name, value);	
	    	}
	    	catch (Exception e) {}
	    }  

	    return map;  
	} 
	
	public static ArrayList<String> patternFind (String str, String regex1, String regex2) {
		ArrayList<String> matchList = new ArrayList<String>();
		ArrayList<String> tempList = new ArrayList<String>();
		Pattern p = Pattern.compile(regex1);
		Matcher m = p.matcher(str);
		while (m.find()) {
			tempList.add(str.substring(m.start(), m.end()));
		}
		
		p = Pattern.compile(regex2);
		for (String match : matchList) {
			m = p.matcher(match);
			while (m.find()) {
				matchList.add(match.substring(m.start(), m.end()));
			}
		}
			
		return matchList;
	}

	public static String removeBlankLine(String str) {
		StringBuffer retLines = new StringBuffer();
		String[] lines = split(str, "\n");
		for (String line : lines) {
			if (line.trim().equals(""))
				continue;
			
			retLines.append(line).append('\n');
		}
		
		return retLines.toString();
	}
	
	public static String[] split(String str, String delimeter) {
		return split(str, delimeter, false, 1);
	}
	
	public static String[] split(String str, String delimeter, boolean isStrict, int minCount) {
		if (str == null)
			return new String[minCount - 1];
		
		StringTokenizer st = new StringTokenizer(str, delimeter, isStrict);
		List<String> resultList = new ArrayList<String>();
		String beforeToken = delimeter;
		while (st.hasMoreTokens()) {
			String token = st.nextToken();
			
			if (token.compareTo(delimeter) == 0 && beforeToken.compareTo(delimeter) == 0) {
				resultList.add("");
			}
			else if (token.compareTo(delimeter) == 0) {
				beforeToken = token;
			}
			else {
				resultList.add(token);
				beforeToken = token;
			}
		}
		
		if (beforeToken.compareTo(delimeter) == 0)
			resultList.add("");
		
		while(resultList.size() < minCount)	resultList.add("");
		
		return resultList.toArray(new String[0]);
	}
	
	public static List<String> splitList(String str, String delimeter) {
		if (str == null)
			return null;
		
		String[] retArray = split(str, delimeter);
		if (retArray == null)
			return null;
			
		List<String> result = new ArrayList<String>();
		for (String value : retArray) {
			if (value == null || value.equals(""))
				continue;
			
			result.add(value);
		}
		
		return result;
	}
	
	public static Long[] splitLong(String str, String delimeter) {
		if (str == null)
			return new Long[0];
		
		StringTokenizer st = new StringTokenizer(str, delimeter);
		List<Long> resultList = new ArrayList<Long>();
		while (st.hasMoreTokens()) {
			String token = st.nextToken();
			try {
				resultList.add(Long.parseLong(token));
			} catch (Exception e) {}
		}
		
		return resultList.toArray(new Long[0]);
	}
	
	public static List<Long> splitLongList(String str, String delimeter) {
		if (str == null)
			return null;
		
		Long[] retArray = splitLong(str, delimeter);
		if (retArray == null)
			return null;
			
		List<Long> result = new ArrayList<Long>();
		for (Long value : retArray) {
			if (value == null || value.equals(""))
				continue;
			
			result.add(value);
		}
		
		return result;
	}
	
	public static Long[] toArrayAsLong(List<String> list) {
		if (list == null || list.size() == 0)
			return null;

		Long[] result = new Long[list.size()];
		
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i) == null)
				continue;
			
			try {
				result[i] = Long.parseLong(list.get(i));
			}
			catch (NumberFormatException e){
				e.printStackTrace();
				continue;
			}
		}
		
		return result;
	}
	
	public static String numberFormat(long number, String format) {
		DecimalFormat decimalFormat = new DecimalFormat(format);

		return decimalFormat.format(number);
	}

	public static String numberFormat(long number) {
		return numberFormat(number, "#,###,###,###,###");
	}

	public static String numberFormat(String number) {
		number = number.replaceAll("[^0-9\\-\\.]", "");

		if (number.equals("")) return "";

		return numberFormat(Integer.parseInt(number));
	}
	
    public static String lpad(String str, int len, String addStr) {
        String result = str;
        int templen   = len - result.length();

        for (int i = 0; i < templen; i++){
              result = addStr + result;
        }
        
        return result;
    }
    
    public static String rpad(String str, int len, String addStr) {
    	String result = str;
    	
    	byte[] b = str.getBytes();
    	int size = b.length;
    	int templen = len - size;
    	for (int i =0 ; i < templen; i++) {
    		result += addStr;
    	}
    	
    	return result;
    }
    
    public static String wrapDoubleQuotation(String value) {
		return "\"" + value + "\"";
	}
	public static String generateHiddenInput(String name, String value) {
		return "<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\">";
	}
	
	public static String startForm(String formName) {
		return "<form name=\"" + formName + "\" method=\"post\">";
	}
	public static String endForm() {
		return "</form>";
	}
	
	public static String getTelNo1(String telNo) {
		if( telNo == null )
			return "";
			
		telNo = telNo.replaceAll("-", "");
	
		if (telNo.length() >= 2 && (telNo.substring(0, 2)).equals("02")) {
			return telNo.substring(0, 2);
		} else if (telNo.length() >= 3) {
			return telNo.substring(0, 3);
		} else
			return "";
	}
	
	public static String getTelNo2(String telNo) {
		telNo = telNo.replaceAll("-", "");
	
		if (telNo.length() >= 9) {
			if ((telNo.substring(0, 2)).equals("02"))
				return telNo.substring(2, (telNo.length() - 4));
			else
				return telNo.substring(3, (telNo.length() - 4));
		} else
			return "";
	}
	
	public static String getTelNo3(String telNo) {
		telNo = telNo.replaceAll("-", "");
	
		if (telNo.length() >= 9)
			return telNo.substring(telNo.length() - 4);
		else
			return "";
	}
	
	/**
	 * 占쌉뤄옙 占쏙옙占쏙옙 MobileNo占쏙옙 占싱듸옙占쏙옙占쏙옙占쏙옙占쏙옙占?확占쏙옙占쏙옙
	 * @param MobileNo
	 * @return boolean
	 */
	
	public static boolean isMobileNumber(String MobileNo) {
		if (MobileNo != null
			&& !MobileNo.equals("")
			&& (MobileNo.equals("010")
				|| MobileNo.equals("011")
				|| MobileNo.equals("016")
				|| MobileNo.equals("017")
				|| MobileNo.equals("018")
				|| MobileNo.equals("019"))) {
			return true;
		} else
			return false;
	}
	
	public static String concatePath(String path1, String path2) {
		if ( path1 == null && path2 == null )	return null;

		path1 = nvl(path1).replace("\\\\", "/");
		path2 = nvl(path2).replace("\\\\", "/");

		if ( path1.equals("") ) return path2;
		if ( path2.equals("") ) return path1;
		
		boolean sep1 = path1.charAt(path1.length()-1) == '/';
		boolean sep2 = path2.charAt(0) == '/'; 

		if ( sep1 && !sep2 || !sep1 && sep2 )	return path1 + path2;
		else if ( !sep1 && !sep2 )				return path1 + "/" + path2;

		return path1.substring(0, path1.length()-1) + path2;
	}
	
	public static String nvl(String value) {
		return nvl(value, "");
	}
	
	public static String nvl(String value, String defaultValue) {
		if (value == null || value.equals(""))	return defaultValue;
		
		return value;
	}
	
	public static boolean isEmpty(Object value) {
		if (value == null || nvl(String.valueOf(value)).equals(""))
			return true;
		
		return false;
	}
	
	public static String getTimestampFormat(String str) {
		if (str == null || str.trim().length() < 8)
			return null;
		
		str = str.trim();
		StringBuffer date = new StringBuffer(); 
		date.append(str.substring(0, 4)).append("-").append(str.substring(4, 6)).append("-").append(str.substring(6, 8)).append(" ");
		String hh = "00";
		String mm = "00";
		String ss = "00";
		
		if (str.length() < 9)
			date.append(hh).append(":").append(mm).append(":").append(ss); 
		else if (str.length() < 11)
			date.append(str.substring(8, 10)).append(":").append(mm).append(":").append(ss);
		else if (str.length() < 13)
			date.append(str.substring(8, 10)).append(":").append(str.substring(10, 12)).append(":").append(ss);
		else if (str.length() < 15)
			date.append(str.substring(8, 10)).append(":").append(str.substring(10, 12)).append(":").append(str.substring(12, 14));
		else
			date.append(str.substring(8, 10)).append(":").append(str.substring(10, 12)).append(":").append(str.substring(12, 14)).append(".").append(str.substring(14, 17));
		
		return date.toString();
	}
	
	public static String getOnlyNumber(String str) {
		return str.replaceAll("[^0-9]", "");
	}
	
	public static String getOnlyNumber(String str, int size) {
		str = str.replaceAll("[^0-9]", "");
		int length = size > str.length() ? str.length() : size;
		
		return str.substring(0, length);
	}

	public static String removePrefix(String str, String prefix) {
		int index = str.indexOf(prefix);
		if (index == 0)
			return str.substring(prefix.length());
		
		return str;
	}
	
	public static String toTimestamp(String dateTime) {
		SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
		try {
			Date date = fromFormat.parse(dateTime);
			return new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(date);
		}
		catch (ParseException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public static void main(String[] args) {
		String test = "file:///test/asdsadasd.png";
		System.out.println(removePrefix(test, "file://"));
	}
}
